# utils.py
import datetime
import json
import os
import re

import psutil


def format_speed(speed):
    if speed is None:
        return "排队中"
    if speed < 1024:
        return f"{speed:.1f}B/s"
    elif speed < 1024 ** 2:
        return f"{speed / 1024:.1f}KB/s"
    else:
        return f"{speed / (1024 ** 2):.1f}MB/s"


def format_size(size):
    if size is None:
        return '0Kb'
    if size < 1024:
        return f"{size}B"
    elif size < 1024 ** 2:
        return f"{size / 1024:.1f}KB"
    elif size < 1024 ** 3:
        return f"{size / (1024 ** 2):.1f}MB"
    else:
        return f"{size / (1024 ** 3):.2f}GB"


def get_status_text(status):
    if status == 1:
        return '完成'
    if status == -1:
        return '下载失败'
    return '排队中'


def is_chrome_running():
    for proc in psutil.process_iter(['name']):
        try:
            if 'chrome' in proc.info['name'].lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            continue
    return False


def build_format_string(selected_format, all_formats: list) -> str:
    selected_format_id = selected_format['format_id']
    # 进一步构建合并格式（如 video+audio 的 f"{v}+{a}"）
    return selected_format_id


# """
# 根据用户选中的 format，自动生成 yt_opts['format'] 可用的字符串。
# 如果选中的格式没有音频，会自动查找最佳音频格式组合。
# """
# selected_format_id = selected_format['format_id']
# has_audio = selected_format.get('acodec') and selected_format['acodec'] != 'none'
#
# if has_audio:
#     # 直接返回该格式 ID
#     return selected_format_id
# else:
#     # 查找一个最优音频格式（只含音频）
#     audio_formats = [
#         f for f in all_formats
#         if f.get('vcodec') == 'none' and f.get('acodec') != 'none'
#     ]
#     if not audio_formats:
#         print("⚠️ 未找到音频格式，将只下载视频。")
#         return selected_format_id
#
#     # 按音频码率排序，优先选更清晰的音频
#     audio_formats.sort(key=lambda f: f.get('abr', 0), reverse=True)
#     best_audio = audio_formats[0]
#
#     return f"{selected_format_id}+{best_audio['format_id']}"

def write_log(data, filename):
    # 确保 logs 目录存在
    log_dir = './logs'
    os.makedirs(log_dir, exist_ok=True)

    # 生成带时间的文件名
    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    full_filename = f"{filename}_{timestamp}.log"
    full_path = os.path.join(log_dir, full_filename)

    # 根据类型决定如何写入
    try:
        with open(full_path, 'w', encoding='utf-8') as f:
            if isinstance(data, (dict, list)):
                json.dump(data, f, ensure_ascii=False, indent=2)
            else:
                f.write(str(data))
        print(f"日志写入成功：{full_path}")
    except Exception as e:
        print(f"写入日志失败：{e}")


def sanitize_filename(name: str) -> str:
    return re.sub(r'[\\/:*?"<>|]', '_', name)
